package middleware

import (
	"sync"

	sentry2 "gitee.com/xuyiping_admin/pkg/sentry"
	"gitee.com/xuyiping_admin/pkg/xerr"

	"github.com/getsentry/sentry-go"
	sentrygin "github.com/getsentry/sentry-go/gin"
	"github.com/gin-gonic/gin"
)

var sentryInitOnce sync.Once

// ReportToSentry report error to sentryhub
func ReportToSentry(dsn string, options ...*sentry.ClientOptions) []gin.HandlerFunc {
	sentryInitOnce.Do(func() {
		sentry2.MustInit(dsn, options...)
	})

	return []gin.HandlerFunc{
		sentrygin.New(sentrygin.Options{Repanic: true}),
		CaptureError,
	}
}

func CaptureError(c *gin.Context) {
	defer func() {
		if len(c.Errors) > 0 {
			if sentryHub := sentrygin.GetHubFromContext(c); sentryHub != nil {
				sentryHub.WithScope(func(scope *sentry.Scope) {
					for _, e := range c.Errors {
						if _, isCustom := xerr.IsCustomError(e); isCustom {
							continue
						}
						_ = sentryHub.CaptureException(e.Err)
					}
				})
			}
			return
		}
	}()
	c.Next()
}
